# -*- coding: utf-8 -*-
from nntpyenc import nntpyencpart, nntpyencwrap
from nntplib import NNTP
from random import SystemRandom
from threading import RLock
from time import time
rand = SystemRandom()

countersLock = RLock()
postbytes = 0
posttime = 0

def get_counters():
	ret = None
	with countersLock:
		global postbytes, posttime
		ret = (postbytes, posttime)
	return ret
def reset_counters():
	with countersLock:
		global postbytes, posttime
		postbytes = 0
		posttime = 0
def inc_counters(bytes, timetaken):
	with countersLock:
		global postbytes, posttime
		postbytes += bytes
		posttime += timetaken

def genmid(part, parts):
	return 'Part%dof%d.%08X%08X%08X%08X@4894782.local' % (part, parts, rand.randint(0, 0xffffffff), rand.randint(0, 0xffffffff), rand.randint(0, 0xffffffff), rand.randint(0, 0xffffffff))

def gensubject(comment, fileno, files, fname, partno, parts):
	return '%s - [%d/%d] - "%s" yEnc (%d/%d)' % (comment, fileno, files, fname, partno, parts)

def postpart(server, port, un, pwd, h_from, h_sender, newsgroups, comment, fileno, files, fname, partno, parts, mid, chars_per_line, lines_per_part, fsize, data):
	t = []
	subject = gensubject(comment, fileno, files, fname, partno, parts)
	headers = 'From: %s\r\nSender: %s\r\nNewsgroups: %s\r\nSubject: %s\r\nMessage-ID: <%s>\r\n\r\n' %\
		(h_from, h_sender, newsgroups, subject, mid)
	# print headers
	t.append(headers)
	encdata, crcstr = nntpyencpart(data, chars_per_line)
	t.append(nntpyencwrap(encdata=encdata, name=fname, pcrc32=crcstr, fsize=fsize, psize=len(data), part=partno, chars_per_line=chars_per_line, lines_per_part=lines_per_part))
	t.append('\r\n.\r\n')
	data_to_post = ''.join(t)
	#
	n = NNTP(server, port, str(un), str(pwd))
	n.shortcmd('POST')
	#
	post_len = len(data_to_post)
	starttime = time()
	#
	n.sock.sendall(data_to_post)
	reply = n.getresp()
	#
	inc_counters(post_len, time() - starttime)
	#
	n.quit()
	
	return reply
